﻿using System;
using System.IO;
using System.Xml;
using System.Web;
using System.Text;
using System.Windows.Forms;
using System.Collections.Generic;

using DreamCube.Foundation.Basic.Utility;
using Top.Api;
using Top.Api.Util;
using Top.Api.Request;
using Top.Api.Response;

namespace DreamCube.TaobaoGJ.BLL
{
    public static class TB_TopClientFunc
    {
        /// <summary>
        /// 根据图片分类名称，获取图片空间的图片分类的ID
        /// </summary>
        /// <param name="categoryName"></param>
        /// <returns></returns>
        public static String GetImageCategoryId(String categoryName)
        {
            PictureCategoryGetRequest req = new PictureCategoryGetRequest
            {
                PictureCategoryName = categoryName
            };
            PictureCategoryGetResponse res = new PictureCategoryGetResponse();
            DefaultTopClient client = TB_AppKeyFunc.GetTopClient();
            res = client.Execute<PictureCategoryGetResponse>(req, SessionKey.GetSessionKey());
            if (res.IsError)
            {
                return String.Empty;
            }
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(res.Body);
            if (doc.SelectSingleNode("picture_category_get_response").InnerText == "")
            {
                return null;
            }
            return doc.SelectSingleNode("picture_category_get_response/picture_categories/picture_category/picture_category_id").InnerText;
        }

        /// <summary>
        /// 创建图片分类
        /// </summary>
        /// <param name="CategoryName">分类名</param>
        /// <param name="parentCategoryID">父级的ID</param>
        /// <returns></returns>
        public static String CreatePictrueCategory(String CategoryName, Int64 parentCategoryID = 0)
        {
            PictureCategoryAddRequest req = new PictureCategoryAddRequest
            {
                PictureCategoryName = CategoryName,
                ParentId = parentCategoryID
            };
            PictureCategoryAddResponse res = new PictureCategoryAddResponse();
            DefaultTopClient client = TB_AppKeyFunc.GetTopClient();
            res = client.Execute<PictureCategoryAddResponse>(req, SessionKey.GetSessionKey());
            if (res.IsError)
            {
                return null;
            }
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(res.Body);
            return doc.SelectSingleNode("picture_category_add_response/picture_category/picture_category_id").InnerText;
        }

        /// <summary>
        /// 添加商品
        /// </summary>
        /// <param name="req">商品数据</param>
        /// <param name="num_iid"></param>
        /// <returns></returns>
        public static Boolean TryAddItem(ItemAddRequest req, out Int64 num_iid)
        {
            num_iid = 0;
            ItemAddResponse res = new ItemAddResponse();
            try
            {
                res = TB_AppKeyFunc.GetTopClient().Execute<ItemAddResponse>(req, SessionKey.GetSessionKey());
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
            if (res.IsError)
            {
                MyLog.MakeLog(res.ErrMsg + res.SubErrMsg);
                return false;
            }
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(res.Body);
            num_iid = Int64.Parse(doc.SelectSingleNode("item_add_response/item/num_iid").InnerText);
            return true;
        }

        /// <summary>
        /// 复制商品
        /// </summary>
        /// <param name="fromNumiid">来源的商品ID</param>
        /// <param name="copyAsSecond">是否已二手发布新的商品</param>
        /// <param name="copyCat">是否复制店铺分类</param>
        /// <param name="num_iid">新生成的商品ID</param>
        /// <returns></returns>
        public static Boolean TryCopyItem(Int64 fromNumiid, Boolean copyAsSecond, Boolean copyCat, out Int64 newNumiid)
        {
            newNumiid = -1;
            XmlDocument doc = new XmlDocument();
            String itemXML = TB_TopClientFunc.GetItem(Properties.Resources.TB_CopyItemField, fromNumiid, String.Empty);
            if (itemXML == null) return false;
            if (itemXML != null)
            {
                ItemAddRequest req = new ItemAddRequest();
                ItemAddResponse res = new ItemAddResponse();
                doc.LoadXml(itemXML);

                //商品数量，取值范围:0-999999的整数。且需要等于Sku所有数量的和 
                req.Num = MyString.ToInt64(MyXml.GetInnerXml(doc, "item_get_response/item/num"));
                if (req.Num > 999999) req.Num = 999998;
                req.Price = MyXml.GetInnerXml(doc, "item_get_response/item/price");
                req.Type = MyXml.GetInnerXml(doc, "item_get_response/item/type");
                req.Title = MyXml.GetInnerXml(doc, "item_get_response/item/title");
                req.LocationState = MyXml.GetInnerXml(doc, "item_get_response/item/location/state");
                req.LocationCity = MyXml.GetInnerXml(doc, "item_get_response/item/location/city");
                req.Cid = MyString.ToInt64(MyXml.GetInnerXml(doc, "item_get_response/item/cid"));
                req.Props = MyXml.GetInnerXml(doc, "item_get_response/item/props");
                req.PropertyAlias = MyXml.GetInnerXml(doc, "item_get_response/item/property_alias");
                req.FreightPayer = MyXml.GetInnerXml(doc, "item_get_response/item/freight_payer");
                req.ValidThru = MyString.ToInt64(MyXml.GetInnerXml(doc, "item_get_response/item/valid_thru"));
                req.HasInvoice = MyString.ToBoolean((MyXml.GetInnerXml(doc, "item_get_response/item/has_invoice")));
                req.HasWarranty = MyString.ToBoolean(MyXml.GetInnerXml(doc, "item_get_response/item/has_warranty"));
                req.HasShowcase = MyString.ToBoolean(MyXml.GetInnerXml(doc, "item_get_response/item/has_showcase"));
                req.OuterId = MyXml.GetInnerXml(doc, "item_get_response/item/outer_id");
                req.ProductId = MyString.ToInt64(MyXml.GetInnerXml(doc, "item_get_response/item/product_id"));
                req.InputPids = MyXml.GetInnerXml(doc, "item_get_response/item/input_pids");
                req.InputStr = MyXml.GetInnerXml(doc, "item_get_response/item/input_str");

                //判断运费模板，如果是使用运费模板的话，先创建一个运费模板
                String yfTemplateID = MyXml.GetInnerText(doc, "item_get_response/item/postage_id");
                String nick = MyXml.GetInnerXml(doc, "item_get_response/item/nick");
                if (yfTemplateID != "0")
                {
                    String newTemplateID;
                    TryAddDeliveryTemplate(yfTemplateID, nick, out newTemplateID);
                    req.PostageId = Int64.Parse(newTemplateID);
                }
                else
                {
                    req.PostFee = MyXml.GetInnerXml(doc, "item_get_response/item/post_fee");
                    req.ExpressFee = MyXml.GetInnerXml(doc, "item_get_response/item/express_fee");
                    req.EmsFee = MyXml.GetInnerXml(doc, "item_get_response/item/ems_fee");
                    //会出现这种情况，当用户使用收费模板时，淘宝不会标志为免邮商品，由于邮费那些不能设置为零，所以有时候会报错。。。
                    //req.PostFee = req.PostFee == "0.00" ? "0.01" : req.PostFee;
                    //req.ExpressFee = req.ExpressFee == "0.00" ? "0.01" : req.ExpressFee;
                    //req.EmsFee = req.EmsFee == "0.00" ? "0.01" : req.EmsFee;
                }
                req.Desc = ChangeDescriptionHtml(MyXml.GetInnerXml(doc, "item_get_response/item/desc"));

                //判断是否以二手发布
                if (copyAsSecond) req.StuffStatus = "second";
                else req.StuffStatus = MyXml.GetInnerXml(doc, "item_get_response/item/stuff_status");

                //商品主图地址
                String picUrl = MyXml.GetInnerXml(doc, "item_get_response/item/pic_url");
                req.Image = null;
                if (!String.IsNullOrEmpty(picUrl))
                {
                    String fileType = "." + MyString.RightOfLast(picUrl, ".");
                    String fileName = MyGuid.To_B(Guid.NewGuid()) + fileType;
                    String fileFullName = Path.Combine(GetTempImagePath(), fileName);
                    if (MyWeb.TryLoadImageFormUrl(picUrl, fileFullName))
                        req.Image = new FileItem(fileFullName);
                }

                //复制店铺类目
                if (copyCat)
                {
                    String seller_cids = MyXml.GetInnerText(doc, "item_get_response/item/seller_cids");
                    String newSellerIDs = String.Empty;
                    CopySellerCat(nick, seller_cids, out newSellerIDs);
                    req.SellerCids = newSellerIDs;
                }

                //先发布商品到淘宝上
                if (!TB_TopClientFunc.TryAddItem(req, out newNumiid)) return false;
                //if (newNumiid < 0) return false;

                //增加商品的图片列表；SKU属性等
                //商品图片列表(包括主图)。fields中只设置item_img可以返回ItemImg结构体中所有字段，如果设置为item_img.id、item_img.url、item_img.position等形式就只会返回相应的字段
                XmlNodeList imageNodeList = doc.SelectNodes("item_get_response/item/item_imgs/item_img");
                if (imageNodeList != null)
                {
                    for (Int32 i = 0; i < imageNodeList.Count; i++)
                    {
                        String imageId = MyXml.GetInnerText((XmlElement)imageNodeList[i], "position");
                        //主图id默认为0，所以可以过滤掉）
                        if (!((imageId == "0") || (String.IsNullOrEmpty(imageId))))
                        {
                            String imageUrl = MyXml.GetInnerText((XmlElement)imageNodeList[i], "url");
                            if (!String.IsNullOrEmpty(imageUrl))
                            {
                                String fileType = "." + MyString.RightOfLast(picUrl, ".");
                                String fileName = MyGuid.To_B(Guid.NewGuid()) + fileType;
                                String fileFullName = Path.Combine(GetTempImagePath(), fileName);
                                if (MyWeb.TryLoadImageFormUrl(imageUrl, fileFullName))
                                    MyImage.MinSize(900, 900, fileFullName, 0x75300);
                                TB_TopClientFunc.TryUploadItemImage(newNumiid, fileFullName, false);
                            }
                        }
                    }
                }

                //商品的SKU
                XmlNodeList skuNodeList = doc.SelectNodes("item_get_response/item/skus/sku");
                if (skuNodeList != null)
                {
                    for (Int32 i = 0; i < skuNodeList.Count; i++)
                    {
                        String properties = MyXml.GetInnerText((XmlElement)skuNodeList[i], "properties");
                        String price = MyXml.GetInnerText((XmlElement)skuNodeList[i], "price");
                        String quantity = MyXml.GetInnerText((XmlElement)skuNodeList[i], "quantity");
                        TB_TopClientFunc.TryAddSku(newNumiid, properties, Int64.Parse(quantity), price);
                    }
                }
            }
            return true;
        }

        /// <summary>
        /// 用于缓存所有的自定义类目
        /// </summary>
        private static Dictionary<String, String> nickSellerCats = new Dictionary<String, String>();

        /// <summary>
        /// 根据类目的ID号，复制类目（多个类目，以逗号隔开）
        /// </summary>
        /// <param name="nick">被复制的店铺ID号</param>
        /// <param name="catIds"></param>
        /// <param name="newCatID"></param>
        /// <returns></returns>
        public static Boolean CopySellerCat(String nick, String catIds, out String newCatID)
        {
            newCatID = String.Empty;
            if (String.IsNullOrEmpty(catIds)) return false;
            String xmlfrom = null;
            //判断缓存中的数据
            if (nickSellerCats.ContainsKey(nick))
            {
                xmlfrom = nickSellerCats[nick];
            }
            else
            {
                xmlfrom = Api.DP_Api.Get_List_Sellercats(nick);
                nickSellerCats.Add(nick, xmlfrom);
            }
            XmlDocument docfrom = new XmlDocument();
            docfrom.LoadXml(xmlfrom);

            //复制到的目标店铺的类目信息
            //先统计现有店铺所有的类目ID和名称
            Dictionary<String, String> toShopAllCatNames = GetShopAllCatNames(SessionKey.SessionNick);

            List<String> returnNewCatIDs = new List<String>(); //记录要收集的商品类目
            String[] catIdList = MyString.RemoveNullOrEmptyItems(catIds.Split(','), null); //商品的类目ID
            XmlNodeList sellerCatList = docfrom.SelectNodes("sellercats_list_get_response/seller_cats/seller_cat");

            for (Int32 j = 0; j < catIdList.Length; j++)
            {
                for (Int32 i = 0; i < sellerCatList.Count; i++)
                {
                    String cid = MyXml.GetInnerText((XmlElement)sellerCatList[i], "./cid");
                    //如果该类目与指定的类目ID匹配，则需要添加到指定的目标店铺中
                    if (cid == catIdList[j])
                    {
                        //先判断目标店铺是否存在同名的类目，如果存在，则直接取其类目的ID即可了
                        String name = MyXml.GetInnerText((XmlElement)sellerCatList[i], "./name");
                        if (toShopAllCatNames.ContainsValue(name))
                        {
                            foreach (KeyValuePair<String, String> item in toShopAllCatNames)
                            {
                                if (item.Value == name)
                                    returnNewCatIDs.Add(item.Key);
                            }
                        }
                        else
                        {
                            //有发生新添加的类目的情况话，要清除缓存了
                            String tempNewCatID;
                            if (TryAddSellerCat(docfrom, cid, SessionKey.SessionNick, out tempNewCatID))
                            {
                                returnNewCatIDs.Add(tempNewCatID);
                                //移除目标店铺的缓存类目项
                                nickSellerCats.Remove(SessionKey.SessionNick);
                                //重新获取缓存中的类目
                                toShopAllCatNames = GetShopAllCatNames(SessionKey.SessionNick);
                            }
                        }
                        break;
                    }
                }
            }
            newCatID = MyEnumerable.JoinEx(returnNewCatIDs, ",");
            return true;
        }

        /// <summary>
        /// 获取店铺的分类名称/id键表
        /// </summary>
        /// <param name="nick"></param>
        /// <returns></returns>
        private static Dictionary<String, String> GetShopAllCatNames(String nick)
        {
            String xml = String.Empty;
            if (nickSellerCats.ContainsKey(nick))
            {
                xml = nickSellerCats[nick];
            }
            else
            {
                xml = Api.DP_Api.Get_List_Sellercats(nick);
                nickSellerCats.Add(nick, xml);
            }
            XmlDocument docTo = new XmlDocument();
            docTo.LoadXml(xml);
            Dictionary<String, String> toShopAllCatNames = new Dictionary<String, String>();
            XmlNodeList catsTo = docTo.SelectNodes("sellercats_list_get_response/seller_cats/seller_cat");
            for (Int32 i = 0; i < catsTo.Count; i++)
            {
                String name = MyXml.GetInnerText((XmlElement)catsTo[i], "./name");
                String cid = MyXml.GetInnerText((XmlElement)catsTo[i], "./cid");
                toShopAllCatNames.Add(cid, name);
            }
            return toShopAllCatNames;
        }

        private static Boolean TryAddSellerCat(XmlDocument from, String catID, String toShopNick, out String newCatID)
        {
            newCatID = String.Empty;
            XmlNodeList sellerCatList = from.SelectNodes("sellercats_list_get_response/seller_cats/seller_cat");
            XmlNode targetNode = null;
            for (Int32 i = 0; i < sellerCatList.Count; i++)
            {
                String cid = MyXml.GetInnerText((XmlElement)sellerCatList[i], "./cid");
                if (cid == catID)
                {
                    targetNode = sellerCatList[i];
                    break;
                }
            }
            String name = MyXml.GetInnerText((XmlElement)targetNode, "./name");
            //一路递归查找到顶级的父类
            Stack<String> allCat = new Stack<String>();
            //把最终的子类目ID添加到栈中
            allCat.Push(catID);
            //判断父ID是否是0，不是0的话，就证明不是顶级的父类目，需要先添加父类目了
            String parentID = MyXml.GetInnerText((XmlElement)targetNode, "./parent_cid");
            while (parentID != "0")
            {
                allCat.Push(parentID);
                for (Int32 k = 0; k < sellerCatList.Count; k++)
                {
                    if (MyXml.GetInnerText((XmlElement)sellerCatList[k], "./cid") == parentID)
                    {
                        parentID = MyXml.GetInnerText((XmlElement)sellerCatList[k], "./parent_cid");
                        break;
                    }
                }
            }

            String newParentCID = "0";
            //反序列出栈，按顺序创建类目
            Dictionary<String, String> toShopAllCatNames = GetShopAllCatNames(toShopNick);
            while (allCat.Count > 0)
            {
                String cid = allCat.Pop();
                for (Int32 k = 0; k < sellerCatList.Count; k++)
                {
                    if (MyXml.GetInnerText((XmlElement)sellerCatList[k], "./cid") == cid)
                    {
                        //递归创建每一个类目的时候，需要判断父类目是否存在了，如果父类存在了，直接获得父类的ID值即可了
                        String picUrl = MyXml.GetInnerText((XmlElement)sellerCatList[k], "./pic_url");
                        String parentName = MyXml.GetInnerText((XmlElement)sellerCatList[k], "./name");
                        if (toShopAllCatNames.ContainsValue(parentName))
                        {
                            foreach (KeyValuePair<String, String> item in toShopAllCatNames)
                            {
                                if (item.Value == parentName)
                                {
                                    newParentCID = item.Key;
                                    break;
                                }
                            }
                            break;
                        }
                        String newPicUrl = String.Empty;
                        if (!String.IsNullOrEmpty(picUrl))
                        {

                        }
                        Top.Api.Domain.SellerCat cat = new Top.Api.Domain.SellerCat
                        {
                            Name = MyXml.GetInnerText((XmlElement)sellerCatList[k], "./name"),
                            ParentCid = Int64.Parse(newParentCID),
                            PicUrl = newPicUrl
                        };

                        TryAddSellerCat(cat, out newParentCID);
                        if (String.IsNullOrEmpty(newParentCID)) newParentCID = "0";
                        break;
                    }
                }
            }
            newCatID = newParentCID;
            return true;
        }

        /// <summary>
        /// 添加类目
        /// </summary>
        /// <param name="cat"></param>
        /// <param name="newCatid"></param>
        /// <returns></returns>
        private static Boolean TryAddSellerCat(Top.Api.Domain.SellerCat cat, out String newCatid)
        {
            newCatid = String.Empty;
            String outXml;
            if (Api.DP_Api.Add_List_Sellercats(cat, out outXml))
            {
                XmlDocument responseDoc = new XmlDocument();
                responseDoc.LoadXml(outXml);
                newCatid = MyXml.GetInnerText(responseDoc, "sellercats_list_add_response/seller_cat/cid");
                return true;
            }
            return false;
        }

        /// <summary>
        /// 获取商品信息
        /// </summary>
        /// <param name="fields">要返回的字段</param>
        /// <param name="id">商品ID</param>
        /// <param name="trackIid"></param>
        /// <returns></returns>
        public static String GetItem(String fields, Int64 id, String trackIid)
        {
            ItemGetRequest req = new ItemGetRequest
            {
                Fields = fields,
                NumIid = id
            };
            if (!String.IsNullOrEmpty(trackIid))
                req.TrackIid = trackIid;
            ItemGetResponse res = new ItemGetResponse();
            res = TB_AppKeyFunc.GetTopClient().Execute<ItemGetResponse>(req);
            if (res.IsError)
            {
                MyLog.MakeLog("TB_TopClientFunc.GetItem()方法异常：" + res.ErrMsg + "-->" + res.SubErrMsg);
                return null;
            }
            return res.Body;
        }

        /// <summary>
        /// 上传商品主图
        /// </summary>
        /// <param name="numiid"></param>
        /// <param name="imagePath"></param>
        /// <param name="isMajor"></param>
        /// <returns></returns>
        public static Boolean TryUploadItemImage(Int64 numiid, String imagePath, Boolean isMajor)
        {
            if (String.IsNullOrEmpty(imagePath)) return false;
            ItemImgUploadRequest req = new ItemImgUploadRequest();
            req.NumIid = numiid;
            req.Image = new FileItem(imagePath);
            req.IsMajor = isMajor;
            ItemImgUploadResponse res = new ItemImgUploadResponse();
            try
            {
                res = TB_AppKeyFunc.GetTopClient().Execute<ItemImgUploadResponse>(req, SessionKey.GetSessionKey());
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
            if (res.IsError)
            {
                MyLog.MakeLog("TryUploadItemImage()方法失败：" + res.ErrMsg + res.SubErrMsg);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 根据运费模板ID号，获取运费模板
        /// </summary>
        /// <param name="templateIDs"></param>
        /// <param name="nick">用户的ID（需要复制的淘宝账号的ID）</param>
        /// <param name="fields"></param>
        /// <returns></returns>
        public static String GetDeliveryTemplate(String templateIDs, String nick, String fields = "")
        {
            if (String.IsNullOrEmpty(fields)) fields = Properties.Resources.TB_CopyYFTemplateField;
            DeliveryTemplateGetRequest req = new DeliveryTemplateGetRequest
            {
                Fields = fields,
                TemplateIds = templateIDs,
                UserNick = nick
            };

            DeliveryTemplateGetResponse response = TB_AppKeyFunc.GetTopClient().Execute<DeliveryTemplateGetResponse>(req);
            if (response.IsError)
            {
                MyLog.MakeLog("TB_TopClientFunc.GetDeliveryTemplate()方法异常：" + response.ErrMsg + "-->" + response.SubErrMsg);
                return null;
            }
            return response.Body;
        }

        /// <summary>
        /// 获取指定用户所有的运费模板
        /// </summary>
        /// <param name="fields"></param>
        /// <returns></returns>
        public static String GetAllDeliveryTemplate(String fields = "")
        {
            if (String.IsNullOrEmpty(fields)) fields = Properties.Resources.TB_CopyYFTemplateField;
            DeliveryTemplatesGetRequest req = new DeliveryTemplatesGetRequest
            {
                Fields = fields
            };

            DeliveryTemplatesGetResponse response = TB_AppKeyFunc.GetTopClient().Execute<DeliveryTemplatesGetResponse>(req, SessionKey.GetSessionKey());
            if (response.IsError)
            {
                MyLog.MakeLog("TB_TopClientFunc.GetAllDeliveryTemplate()方法异常：" + response.ErrMsg + "-->" + response.SubErrMsg);
                return null;
            }
            return response.Body;
        }

        /// <summary>
        /// 添加运费模板
        /// </summary>
        /// <param name="req"></param>
        /// <param name="newTemplateID">返回新增的模板的ID号</param>
        public static Boolean TryAddDeliveryTemplate(DeliveryTemplateAddRequest req, out String newTemplateID)
        {
            newTemplateID = "0";
            DeliveryTemplateAddResponse response = null;
            try
            {
                response = TB_AppKeyFunc.GetTopClient().Execute(req, SessionKey.GetSessionKey());
                String xml = response.Body;
                if (response.IsError)
                {
                    MyLog.MakeLog("TB_TopClientFunc.TryAddDeliveryTemplate()方法异常：" + response.ErrMsg + "-->" + response.SubErrMsg);
                    return false;
                }
                if (!String.IsNullOrEmpty(xml))
                {
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(xml);
                    newTemplateID = MyXml.GetInnerText(doc, "delivery_template_add_response/delivery_template/template_id");
                    return true;
                }
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
                return false;
            }
            return false;
        }

        /// <summary>
        /// 添加SKU到指定的商品
        /// </summary>
        /// <param name="numiid">商品ID</param>
        /// <param name="properties">属性字符串</param>
        /// <param name="quantity">sku库存</param>
        /// <param name="price">价格</param>
        /// <param name="outerid"></param>
        /// <returns></returns>
        public static Boolean TryAddSku(Int64 numiid, String properties, Int64 quantity, String price,String outerid = "", String globalLg = "zh_CN")
        {
            ItemSkuAddRequest req = new ItemSkuAddRequest();
            req.NumIid = numiid;
            req.Properties = properties;
            req.Quantity = quantity;
            req.Price = price;
            req.Lang = globalLg;
            if (!String.IsNullOrEmpty(outerid)) req.OuterId = outerid;
            ItemSkuAddResponse res = new ItemSkuAddResponse();
            try
            {
                res = TB_AppKeyFunc.GetTopClient().Execute<ItemSkuAddResponse>(req, SessionKey.GetSessionKey());
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
                return false;
            }
            if (res.IsError)
            {
                MyLog.MakeLog("TryAddSku()方法失败：" + res.ErrMsg +  res.SubErrMsg);
                return false;
            }
            return true;
        }

        /// <summary>
        /// 创建相同的运费模板，当然，根据运费模板名称来判断，如果纯在同名的运费模板，则不要再创建了
        /// </summary>
        /// <param name="yfTemplateID"></param>
        /// <param name="nick">运费模板来源的店铺ID号</param>
        /// <param name="newTemplateID">返回新创建的运费模板ID号</param>
        public static Boolean TryAddDeliveryTemplate(String yfTemplateID, String nick, out String newTemplateID)
        {
            newTemplateID = "-1";
            try
            {
                //template_id：查询模板ID 
                //template_name:查询模板名称 
                String yfTemplateItem = GetDeliveryTemplate(yfTemplateID, nick); //获取模板数据回来
                String yfTemplateName = "";
                XmlDocument yfTemplateXml = new XmlDocument();
                if (!String.IsNullOrEmpty(yfTemplateItem))
                {
                    yfTemplateXml.LoadXml(yfTemplateItem);
                    yfTemplateName = MyXml.GetInnerText(yfTemplateXml, "delivery_template_get_response/delivery_templates/delivery_template/name");
                }
                //获取授权网店已经存在的所有运费模板（如果存在同名的模板，则返回该模板ID号就行了）
                String existAllXml = GetAllDeliveryTemplate("template_id,template_name");
                if (!String.IsNullOrEmpty(existAllXml))
                {
                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(existAllXml);

                    XmlNodeList templateNodeList = doc.SelectNodes("/delivery_templates_get_response/delivery_templates/delivery_template");
                    for (Int32 i = 0; i < templateNodeList.Count; i++)
                    {
                        String templateName = MyXml.GetInnerText((XmlElement)templateNodeList[i], "./name");
                        if (templateName == yfTemplateName)
                        {
                            String templateID = MyXml.GetInnerText((XmlElement)templateNodeList[i], "./template_id");
                            newTemplateID = templateID;
                            return true;
                        }
                    }
                }
                DeliveryTemplateAddRequest req = new DeliveryTemplateAddRequest
                {
                    //可选值：0,1 说明 0:表示买家承担服务费; 1:表示卖家承担服务费
                    Assumer = Int64.Parse(MyXml.GetInnerText(yfTemplateXml, "delivery_template_get_response/delivery_templates/delivery_template/assumer")),
                    //该模板上设置的卖家发货地址区域ID，如：address为浙江省杭州市西湖去文三路XX号那么这个consign_area_id的值就是西湖区的ID
                    ConsignAreaId = Int64.Parse(MyXml.GetInnerText(yfTemplateXml, "delivery_template_get_response/delivery_templates/delivery_template/consign_area_id")),
                    Name = MyXml.GetInnerText(yfTemplateXml, "delivery_template_get_response/delivery_templates/delivery_template/name"),
                    //可选值：0 说明： 0:表示按宝贝件数计算运费 1:表示按宝贝重量计算运费 3:表示按宝贝体积计算运费
                    Valuation = Int64.Parse(MyXml.GetInnerText(yfTemplateXml, "delivery_template_get_response/delivery_templates/delivery_template/valuation"))

                    //注意:在添加多个运费方式时,字符串中使用 ";" 分号区分 。
                    //template_dests(指定地区) 
                    //template_start_standards(首费标准)、
                    //template_start_fees(首费)、
                    //template_add_standards(增费标准)、
                    //template_add_fees(增费)
                    //必须与template_types的分号数量相同. 
                    //TemplateAddFees = MyXml.GetInnerText(yfTemplateXml, "delivery_template_get_response/delivery_templates/delivery_template/fee_list/top_fee/add_fee"),
                    //TemplateAddStandards = MyXml.GetInnerText(yfTemplateXml, "delivery_template_get_response/delivery_templates/delivery_template/fee_list/top_fee/add_standard"),
                    //TemplateDests = MyXml.GetInnerText(yfTemplateXml, "delivery_template_get_response/delivery_templates/delivery_template/fee_list/top_fee/destination"),
                    //TemplateStartFees = MyXml.GetInnerText(yfTemplateXml, "delivery_template_get_response/delivery_templates/delivery_template/fee_list/top_fee/start_fee"),
                    //TemplateStartStandards = MyXml.GetInnerText(yfTemplateXml, "delivery_template_get_response/delivery_templates/delivery_template/fee_list/top_fee/start_standard"),
                };
                XmlNodeList feeList = yfTemplateXml.SelectNodes("delivery_template_get_response/delivery_templates/delivery_template/fee_list/top_fee");
                List<String> types = new List<String>();
                Dictionary<String, List<String>> addFeeListItems = new Dictionary<String, List<String>>();
                Dictionary<String, List<String>> standardListItems = new Dictionary<String, List<String>>();
                Dictionary<String, List<String>> desionationListItems = new Dictionary<String, List<String>>();
                Dictionary<String, List<String>> startFeeListItems = new Dictionary<String, List<String>>();
                Dictionary<String, List<String>> startStandardListItems = new Dictionary<String, List<String>>();
                for (Int32 i = 0; i < feeList.Count; i++)
                {
                    //添加服务类型
                    String serviceType = MyXml.GetInnerText((XmlElement)feeList[i], "./service_type");
                    MyList.AddItem(types, serviceType);

                    String addFee = MyXml.GetInnerText((XmlElement)feeList[i], "./add_fee");
                    String standard = MyXml.GetInnerText((XmlElement)feeList[i], "./add_standard");
                    String desionation = MyXml.GetInnerText((XmlElement)feeList[i], "./destination");
                    desionation = desionation.Replace(",", "|");
                    String startFee = MyXml.GetInnerText((XmlElement)feeList[i], "./start_fee");
                    String startStandard = MyXml.GetInnerText((XmlElement)feeList[i], "./start_standard");

                    if (addFeeListItems.ContainsKey(serviceType))
                    {
                        addFeeListItems[serviceType].Add(addFee);
                        standardListItems[serviceType].Add(standard);
                        desionationListItems[serviceType].Add(desionation);
                        startFeeListItems[serviceType].Add(startFee);
                        startStandardListItems[serviceType].Add(startStandard);
                    }
                    else
                    {
                        List<String> addFeeList = new List<String>();
                        List<String> standardList = new List<String>();
                        List<String> desionationList = new List<String>();
                        List<String> startFeeList = new List<String>();
                        List<String> startStandardList = new List<String>();

                        addFeeListItems.Add(serviceType, addFeeList);
                        standardListItems.Add(serviceType, standardList);
                        desionationListItems.Add(serviceType, desionationList);
                        startFeeListItems.Add(serviceType, startFeeList);
                        startStandardListItems.Add(serviceType, startStandardList);

                        addFeeList.Add(addFee);
                        standardList.Add(standard);
                        desionationList.Add(desionation);
                        startFeeList.Add(startFee);
                        startStandardList.Add(startStandard);
                    }
                }
                req.TemplateTypes = MyEnumerable.JoinEx(types, ";");
                req.TemplateAddFees = JoinTemplateData(addFeeListItems);
                req.TemplateAddStandards = JoinTemplateData(standardListItems);
                req.TemplateDests = JoinTemplateData(desionationListItems);
                req.TemplateStartFees = JoinTemplateData(startFeeListItems);
                req.TemplateStartStandards = JoinTemplateData(startStandardListItems);

                return TryAddDeliveryTemplate(req, out newTemplateID);
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
                return false;
            }
        }

        #region "私有方法"

        /// <summary>
        /// 获取图片临时保存目录
        /// </summary>
        /// <returns></returns>
        private static String GetTempImagePath()
        {
            String path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Images\" + MyDatetime.FormatToDay(DateTime.Now));
            MyIO.EnsurePath(path);
            return path;
        }

        /// <summary>
        /// 切换商品描述的图片路径（把别人的图片上传到自己的空间）
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        private static String ChangeDescriptionHtml(String html)
        {
            WebBrowser webclient = new WebBrowser();
            String TS = HttpUtility.HtmlDecode(html);
            webclient.DocumentText = TS;
            HtmlDocument document1 = webclient.Document;
            document1.Write(TS);

            //去掉所有的超链接
            HtmlElementCollection a_elements = document1.GetElementsByTagName("a");
            if (a_elements != null && a_elements.Count > 0)
            {
                for (Int32 i = 0; i < a_elements.Count; i++)
                    a_elements[i].SetAttribute("href", "#");
            }
            //处理所有背景图片的情况
            String tempHtml = document1.Body.InnerHtml;
            document1.Body.InnerHtml = ParseBackgroundImg(tempHtml);

            //搬家所有图片
            HtmlElementCollection img_elements = document1.GetElementsByTagName("img");
            UploadImage(img_elements);
            return document1.Body.InnerHtml;
        }

        /// <summary>
        /// 解析背景图的情况
        /// </summary>
        /// <param name="html"></param>
        /// <returns></returns>
        private static String ParseBackgroundImg(String html)
        {
            String[] bgImages = MyString.SubStringBetweenStr(html, "background=", " ", false, false);
            if (bgImages != null && bgImages.Length > 0)
            {
                for (Int32 i = 0; i < bgImages.Length; i++) 
                {
                    if (bgImages[i].StartsWith("http://img"))
                        html = html.Replace(bgImages[i], CopyImageToMyShop(bgImages[i]));
                }
            }
            return html;
        }

        /// <summary>
        /// 组合运费模板的
        /// </summary>
        /// <param name="inputs"></param>
        /// <returns></returns>
        private static String JoinTemplateData(Dictionary<String, List<String>> inputs, String itemsDiv = ";", String innerItemsDiv = ",")
        {
            StringBuilder sb = new StringBuilder();
            Int32 i = 0;
            foreach (KeyValuePair<String, List<String>> item in inputs)
            {
                if (i++ == 0)
                {
                    sb.Append(MyEnumerable.JoinEx(item.Value, innerItemsDiv));
                }
                else
                {
                    sb.Append(itemsDiv + MyEnumerable.JoinEx(item.Value, innerItemsDiv));
                }
            }
            return sb.ToString();
        }

        private static String DownLoadImage(String url)
        {
            //图片的保存目录
            String picPath = GetTempImagePath();
            String imageSrc = url;
            String imageType = "." + MyString.RightOfLast(imageSrc, ".").ToLower();
            String imageFileName = MyGuid.To_N(Guid.NewGuid()) + imageType;
            String picFileFullName = Path.Combine(picPath, imageFileName);
            if (MyWeb.TryLoadImageFormUrl(imageSrc, picFileFullName)) return picFileFullName;
            return String.Empty;
        }

        /// <summary>
        /// 根据图片的文件路径上传图片
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        private static String UploadImage(String filePath)
        {
            FileItem fileItem = new FileItem(filePath);
            PictureUploadRequest req = new PictureUploadRequest();
            String parentID = TB_TopClientFunc.GetImageCategoryId(Properties.Resources.ImageCategoryName);
            if (String.IsNullOrEmpty(parentID))
            {
                parentID = TB_TopClientFunc.CreatePictrueCategory(Properties.Resources.ImageCategoryName);
                req.PictureCategoryId = Int64.Parse(parentID);
            }
            else
            {
                req.PictureCategoryId = Int64.Parse(parentID);
            }
            req.Img = fileItem;
            req.ImageInputTitle = MyString.LeftOfLast(filePath, ".");
            PictureUploadResponse res = new PictureUploadResponse();
            try
            {
                res = TB_AppKeyFunc.GetTopClient().Execute<PictureUploadResponse>(req, SessionKey.GetSessionKey());
            }
            catch (Exception ex)
            {
                MyLog.MakeLog(ex);
            }
            if (!res.IsError)
            {
                XmlDocument xmldoc = new XmlDocument();
                xmldoc.LoadXml(res.Body);
                String reslutPicAddress = xmldoc.SelectSingleNode("picture_upload_response/picture/picture_path").InnerText;
                return reslutPicAddress;
            }
            return String.Empty;
        }

        /// <summary>
        /// 根据图片的Url，复制图片到自己的店铺上
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        private static String CopyImageToMyShop(String url)
        {
            String picFileFullName = DownLoadImage(url);
            if (!String.IsNullOrEmpty(picFileFullName))
            {
                String reslutPicAddress = UploadImage(picFileFullName);
                return reslutPicAddress;
            }
            return String.Empty;
        }

        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="img_elements"></param>
        private static void UploadImage(HtmlElementCollection img_elements)
        {
            if (img_elements != null && img_elements.Count > 0)
            {
                for (Int32 i = 0; i < img_elements.Count; i++)
                {
                    //下载图片
                    String imageSrc = img_elements[i].GetAttribute("src");
                    String reslutPicAddress = CopyImageToMyShop(imageSrc);
                    img_elements[i].SetAttribute("src", reslutPicAddress);
                }
            }
        }

        #endregion
    }
}
